import { ref } from 'vue';
import { getGlobalMap } from '../olMap';
import { addPolygonLayer } from 'gmap-ol';
import { getBoundaryJson } from '@/api/mapServices/geojson';

import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { Polygon } from 'ol/geom';
import { Fill, Style } from 'ol/style';
import Feature from 'ol/Feature';
import { GeoJSON } from 'ol/format';

const globalMap = ref<any>(null);

// 添加需要的地图数据
export const addMapData = () => {
  globalMap.value = getGlobalMap();
  addBoundaryLayerData();
}

const addBoundaryLayerData = async() => {
  const olMap = globalMap.value;
  const boundaryJson = await getBoundaryJson();
  const geojsonFormat = new GeoJSON();
  const features = geojsonFormat.readFeatures(boundaryJson);

  // 创建一个遮罩层
  const mask = new Polygon([[
    [-10.46527138, 73.48800655 ], [-10.46527138, -31.653669724 ], [211.67602760, -31.653669724 ], [211.67602760, 73.48800655 ], [-10.46527138, 73.48800655 ]
  ]]);

  // 从遮罩层中减去你的边界数据
  features.forEach((feature) => {
    const geometry: any = feature.getGeometry();
    for (let i = 0; i < geometry.getPolygons().length; i++) {
      const polygon = geometry.getPolygon(i);
      mask.appendLinearRing(polygon.getLinearRing(0));
    }
  });

  // 创建一个VectorLayer，并将遮罩层添加到其中
  const maskDarkLayer = new VectorLayer({
    source: new VectorSource({
      features: [new Feature(mask)]
    }),
    visible: true,
    style: new Style({
      fill: new Fill({
        color: 'rgba(0, 0, 0, 0.5)'
      }),
    })
  });

  maskDarkLayer.set('layerName', `maskDarkLayer`);
  olMap.addLayer(maskDarkLayer);

  olMap.getView().animate({
    center: [118.947055, 32.322297],   //平移到点，有缓动效果
    duration: 1000,   //动画时间
    zoom: 13.5    //设置地图视图层级大小
  });

  const polygonOptions = {
    layerName: 'MaskBoundaryPolygonLayer',
    zIndex: 10,
    textFieldName: 'name',
    styles: {
      fill: {
        color: 'rgba(0, 0, 0, 0)'
      },
      stroke: {
        width: 3,
        color: 'rgba(200, 168, 210, 0.8)',  // rgba(185, 171, 120, 1)
        // lineDash: [10, 10]
      },
    }
  };

  // 把数据加载在地图上
  addPolygonLayer(olMap, boundaryJson, polygonOptions);
}
